import json
import re
import logging

from requests import Response
from rest_framework import serializers
from rest_framework.views import APIView

from carts.utils import merge_cart_cookie_to_redis
from goods.models import SKU

logger = logging.getLogger('django')
from django import http
from django.contrib.auth import login, authenticate, logout
from django.http import JsonResponse, HttpResponse, HttpResponseForbidden
from django.shortcuts import render
from django_redis import get_redis_connection
from django.views import View
from meiduo_mall.utils.view import LoginRequiredMixin
from users.models import User, Address, UserModelSerializer


class UserSerializerView(APIView):
    def get(self, request):
        # user = User.objects.get(id=request.user.id)
        user = User.objects.get(id=request.user.id)

        serializers = UserModelSerializer(user)
        print(serializers.data)
        info_data = {
            'username': serializers.data['username'],
            'mobile': serializers.data['mobile'],
            'email': serializers.data['email'],
            'email_active': serializers.data['email_active']
        }

        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'info_data': serializers.data
        })


class UsernameCountView(View):
    def get(self, request, username):

        # 查看数据库的比较
        try:
            count = User.objects.filter(username=username).count()

        except Exception as E:
            return JsonResponse({
                'code': 400,
                'errmsg': 'fail'

            })

        return JsonResponse({
            'code': 200,
            'errmsg': "ok",
            'count': count
        })


class MobileCount(View):
    def get(self, request, mobile):
        '''判断手机号是否重复注册'''
        try:
            count = User.objects.filter(mobile=mobile).count()

        except Exception as e:
            return JsonResponse({
                'code': 400,
                'errmsg': 'NG',

            })
        return JsonResponse({
            'code': 200,
            'errmsg': 'OK',
            'count': count,
        })


class Register(View):
    def post(self, request):

        str = request.body.decode()
        dict = json.loads(str)

        username = dict.get('username')
        password = dict.get('password')
        password2 = dict.get('password2')
        mobile = dict.get('mobile')
        sms_code = dict.get('sms_code')
        allow = dict.get('allow')

        if not re.match(r'^\w{5,20}$', username):
            return http.JsonResponse({
                'code': 400,
                'errmsg': '用户名不符合要求'
            })
        if not re.match(r'^\w{5,20}$', password):
            return http.JsonResponse({
                'code': 400,
                'errmsg': '密码格式不正确'
            })
        if password != password2:
            return http.JsonResponse({
                'code': 400,
                'errmsg': '两次输入的密码不同'
            })

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({
                'code': 400,
                'errmsg': '电话号码不正确'
            })
        if allow != True:
            return http.JsonResponse({
                'code': 400,
                'errmsg': '需要勾选同意'
            })

        redis_conn = get_redis_connection('verify_code')

        sms_code_server = redis_conn.get('sms_%s' % mobile)

        if not sms_code_server:
            return http.JsonResponse({
                'code': 400,
                'errmsg': '验证码已过期'
            })
        if sms_code != sms_code_server.decode():
            return http.JsonResponse({
                'code': 400,
                'errmsg': '验证码有误'
            })

        try:
            user = User.objects.create_user(username=username,
                                            password=password,
                                            mobile=mobile)
        except Exception as e:
            return http.JsonResponse({
                'code': 400,
                'errmsg': '数据库出错'
            })

        login(request, user)

        response = JsonResponse({
            'code': 0,
            'errmsg': 'ok'
        })

        response = merge_cart_cookie_to_redis(request=request, user=user, response=response)

        return response


class LoginView(View):

    def post(self, request):

        dict = json.loads(request.body.decode())

        username = dict.get('username')
        password = dict.get('password')
        remembered = dict.get('remembered')

        if not all([username, password]):
            return JsonResponse({
                'code': 400,
                'errmsg': '缺少必传参数'
            })

        if re.match(r'1[3-9]\d{9}$', username):
            try:
                count = User.objects.get(mobile=username).count()
                if count == 0:
                    return JsonResponse({
                        'code': 400,
                        'errmsg': '号码未注册'
                    })

                username = User.objects.get(mobile=username)
            except Exception as e:
                return JsonResponse({
                    'code': 400,
                    'errmsg': '缺少必传参数'
                })

        user = authenticate(username=username,
                            password=password)

        login(request, user)

        if remembered is False:

            request.session.set_expiry(0)
        else:
            request.session.set_expiry(None)

        response = JsonResponse({
            'code': 0,
            'errmsg': 'ok'
        })

        response.set_cookie('username', user.username, max_age=3600)
        response = merge_cart_cookie_to_redis(request, user, response)

        return response


class LogoutView(View):

    def delete(self, request):
        logout(request)

        response = JsonResponse({
            'code': 0,
            'errmsg': 'ok'
        })

        response.delete_cookie('username')

        return response


# 给该类视图增加 Mixin 扩展类
class UserInfoView(LoginRequiredMixin, View):
    """用户中心"""

    def get(self, request):
        info_data = {
            'username': request.user.username,
            'mobile': request.user.mobile,
            'email': request.user.email,
            'email_active': request.user.email_active,
        }
        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'info_data': info_data,
        })


class EmailView(View):
    def put(self, request):

        json_dict = json.loads(request.body.decode())
        email = json_dict.get('email')

        if not email:
            return JsonResponse({
                'code': 400,
                'errmsg': '请输入邮箱'
            })
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return JsonResponse({
                'code': 400,
                'errmsg': '邮箱格式错误'
            })
        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({
                'code': 400,
                'errmsg': '添加邮箱失败'
            })

        from celery_tasks.email.tasks import send_verify_email
        verify_url = request.user.generate_verify_email_url()

        send_verify_email.delay(email, verify_url)

        return JsonResponse({
            'code': 0,
            'errmsg': '添加邮箱成功'
        })


class VerifyEmailView(View):
    def put(self, request):
        token = request.GET.get('token')

        if not token:
            return JsonResponse({
                'code': 400,
                'errmsg': '缺少必传参数'
            })
        user = User.check_verify_email_token(token)

        if not user:
            return JsonResponse({
                'code': 400,
                'errmsg': '无效的token'
            })
        try:
            user.email_active = True
            user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({
                'code': 400,
                'errmsg': '激活邮件失败'
            })
        return JsonResponse({
            'code': 0,
            'errmsg': 'ok'
        })


class CreateAddressView(View):
    def post(self, request):

        try:
            count = Address.objects.filter(user=request.user,
                                           is_deleted=False).count()
            if count >= 20:
                return JsonResponse({
                    'code': 400,
                    'errmsg': '地址不能超过20'
                })
        except Exception as e:
            return JsonResponse({
                'code': 400,
                'errmsg': '数据查询出错'
            })

        json_list = json.loads(request.body.decode())

        receiver = json_list.get('receiver')
        province_id = json_list.get('province_id')
        city_id = json_list.get('city_id')
        district_id = json_list.get('district_id')
        place = json_list.get('place')
        mobile = json_list.get('mobile')
        tel = json_list.get('tel')
        email = json_list.get('email')

        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({
                'code': 400,
                'errmsg': '缺少必传参数'
            })

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '参数mobile有误'})

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.JsonResponse({'code': 400,
                                          'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.JsonResponse({'code': 400,
                                          'errmsg': '参数email有误'})

        try:
            address = Address.objects.create(
                user=request.user,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
            if not request.user.default_address:
                request.user.default_address = address
                request.user.save()
        except Exception as e:
            return JsonResponse({
                'code': 400,
                'errmsg': '添加到数据库错误'
            })

        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        # 响应保存结果
        return http.JsonResponse({'code': 0,
                                  'errmsg': '新增地址成功',
                                  'address': address_dict})


class AddressView(View):
    def get(self, request):

        try:
            address_list = []
            address_all = Address.objects.filter(user=request.user,
                                                 is_deleted=False)

            for address in address_all:
                name = {
                    "id": address.id,
                    "title": address.title,
                    "receiver": address.receiver,
                    "province": address.province.name,
                    "city": address.city.name,
                    "district": address.district.name,
                    "place": address.place,
                    "mobile": address.mobile,
                    "tel": address.tel,
                    "email": address.email}
                default_address = request.user.default_address
                if default_address.id == address.id:
                    address_list.insert(0, name)
                else:
                    address_list.append(name)
        except Exception as e:
            return JsonResponse({
                'code': 400,
                'errmsg': '展示错误'
            })
        default_id = request.user.default_address_id
        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'default_address_id': default_id,
            'addresses': address_list
        })


class UpdateDestroyAddressView(View):
    def put(self, request, address_id):
        json_list = json.loads(request.body.decode())
        receiver = json_list.get('receiver')
        province_id = json_list.get('province_id')
        city_id = json_list.get('city_id')
        district_id = json_list.get('district_id')
        place = json_list.get('place')
        mobile = json_list.get('mobile')
        tel = json_list.get('tel')
        email = json_list.get('email')
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({
                'code': 400,
                'errmsg': '缺少必传参数'
            })

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '参数mobile有误'})

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.JsonResponse({'code': 400,
                                          'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.JsonResponse({'code': 400,
                                          'errmsg': '参数email有误'})

        try:
            address = Address.objects.filter(id=address_id)

            address.update(user=request.user,
                           receiver=receiver,
                           province_id=province_id,
                           city_id=city_id,
                           district_id=district_id,
                           place=place,
                           mobile=mobile,
                           tel=tel,
                           email=email)
            # address.save()
        except Exception as e:
            return JsonResponse({
                'code': 400,
                'errmsg': '修改失败'
            })
        address = Address.objects.get(id=address_id)
        address_dict = {"id": address.id,
                        "title": address.title,
                        "receiver": address.receiver,
                        "province": address.province.name,
                        "city": address.city.name,
                        "district": address.district.name,
                        "place": address.place,
                        "mobile": address.mobile,
                        "tel": address.tel,
                        "email": address.email}
        return JsonResponse({
            'code': 0,
            'errmsg': '修改成功',
            'address': address_dict
        })

    def delete(self, request, address_id):

        try:
            address = Address.objects.get(id=address_id)
            address.is_deleted = True
            address.save()
        except Exception as e:
            return JsonResponse({
                'code': 400,
                'errmsg': '删除失败',
            })
        return JsonResponse({
            'code': 0,
            'errmsg': '删除成功'
        })


class DefaultAddressView(View):
    def put(self, request, address_id):

        try:
            address = Address.objects.get(id=address_id)
            # request.user.default_address = address
            request.user.default_address_id = address.id
            request.user.save()
        except Exception as e:
            return JsonResponse({
                'code': 400,
                'errmsg': '设置失败'
            })
        return JsonResponse({
            'code': 0,
            'errmsg': '设置成功'
        })


class UpdateTitleAddressView(View):
    def put(self, request, address_id):
        json_list = json.loads(request.body.decode())

        title = json_list.get('title')

        try:
            Address.objects.filter(id=address_id).update(title=title)

        except Exception as e:
            return JsonResponse({
                'code': 400,
                'errmsg': '更新标题失败'
            })
        return JsonResponse({
            'code': 0,
            'errmsg': '更新标题成功'
        })


class ChangePasswordView(View):
    def put(self, request):
        json_list = json.loads(request.body.decode())
        old_password = json_list.get('old_password')
        new_password = json_list.get('new_password')
        new_password2 = json_list.get('new_password2')

        if not request.user.check_password(old_password):
            return JsonResponse({
                'code': 400,
                'errmsg': '输入的原密码错误'
            })
        if new_password != new_password2:
            return JsonResponse({
                'code': 400,
                'errmsg': '两次输入的密码不符'
            })

        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_password):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '密码最少8位,最长20位'})
        try:
            request.user.set_password(new_password)
            request.user.save()
        except Exception as e:
            return JsonResponse({
                'code': 400,
                'errmsg': '设置密码失败'
            })
        logout(request)
        response = JsonResponse({
            'code': 0,
            'errmsg': '密码设置成功'
        })

        response.delete_cookie('username')

        return response


class UserBrowseHistory(View):
    def post(self, request):

        dict = json.loads(request.body.decode())

        sku_id = dict.get('sku_id')

        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return HttpResponseForbidden('sku不存在')

        redis_conn = get_redis_connection('history')

        pl = redis_conn.pipeline()

        user_id = request.user.id

        pl.lrem('history_%s' % user_id, 0, sku_id)
        pl.lpush('history_%s' % user_id, sku_id)
        pl.ltrim('history_%s' % user_id, 0, 4)

        pl.execute()

        return JsonResponse({
            'code': 0,
            'errmsg': 'ok'
        })

    def get(self, request):

        redis_conn = get_redis_connection('history')

        sku_ids = redis_conn.lrange('history_%s' % request.user.id, 0, -1)

        skus = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            skus.append({
                'id': sku.id,
                'name': sku.name,
                'default_image_url': sku.default_image_url,
                'price': sku.price
            })

        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'skus': skus
        })
